(function($){
	
	$.fn.jTable = function(options){
		
		return this.each(function(){
			
		 	var $table = $(this), nowrapTD = $table.attr("nowrapTD");
		 	var tlength = $table.width();
			var aStyles = [];
			var $tc = $table.parent().addClass("j-resizeGrid"); // table parent container
			var layoutH = $(this).attr("layoutH");

			var oldThs = $table.find("thead>tr:last-child").find("th");

			for(var i = 0, l = oldThs.size(); i < l; i++) {
				var $th = $(oldThs[i]);
				var style = [], width = $th.innerWidth() - (100 * $th.innerWidth() / tlength)-2;
				style[0] = parseInt(width);
				style[1] = $th.attr("align");
				aStyles[aStyles.length] = style;
			}
			
			$(this).wrap("<div class='grid'></div>");
			var $grid = $table.parent().html($table.html());
			var thead = $grid.find("thead");
			thead.wrap("<div class='gridHeader'><div class='gridThead'><table style='width:" + (tlength - 20) + "px;'></table></div></div>");

			var lastH = $(">tr:last-child", thead);
			var ths = $(">th", lastH);
			$("th",thead).each(function(){
				var $th = $(this);
				$th.html("<div class='gridCol' title='"+$th.text()+"'>"+ $th.html() +"</div>");	
			});
			
			ths.each(function(i){
				var $th = $(this), style = aStyles[i];
				$th.addClass(style[1]).hoverClass("hover").removeAttr("align").removeAttr("width").width(style[0]);
			}).filter("[orderField]").orderBy({
				targetType: $table.attr("targetType"),
				rel:$table.attr("rel"),
				asc: $table.attr("asc") || "asc",
				desc:  $table.attr("desc") || "desc"
			});

			var $tbody = $grid.find(">tbody");
			//找到经过html包裹之后的tbody的对象
			
			var layoutStr = layoutH ? " layoutH='" + layoutH + "'" : "";
			
			$tbody.wrap("<div class='gridScroller'" + layoutStr + " style='width:" + $tc.width() + "px;'><div class='gridTbody'><table style='width:" + (tlength - 20) + "px;'></table></div></div>");
			var ftr = $(">tr:first-child", $tbody);
			
			var $tbodyTrList = $tbody.find('>tr');
			//找到经过tbody对象的tr的列表
			
			$tbodyTrList.hoverClass().each(function(){
				
				var $tbodyTr = $(this); 
				
				//这个地方将无限分类的tr添加一些无限分类的内容
				if($tbodyTr.hasClass('unlimitedList')){
				//把原来页面内容添加一些格式化控制的内容，如file、folder、item、indent、line等等
					_initUnlimitedTr($tbodyTr);
					_bindUnlimitedTr($tbodyTr);
				}
				
				_initNormalTr($tbodyTr);
				
				_bindEachTrClickEvent($tbodyTr);
				
				var $progressBar = $tbodyTr.find('td.progress');
				var $percent 	 = $progressBar.text();
				$progressBar.progress($percent);
				
				
			});
			
			
			$(">td",ftr).each(function(i){
				if (i < aStyles.length) $(this).width(aStyles[i][0]);
			});	
			
			$grid.append("<div class='resizeMarker' style='height:300px; left:57px;display:none;'></div><div class='resizeProxy' style='height:300px; left:377px;display:none;'></div>");
	
			var scroller = $(".gridScroller", $grid);
			scroller.scroll(function(event){
				var header = $(".gridThead", $grid);
				if(scroller.scrollLeft() > 0){
					header.css("position", "relative");
					var scroll = scroller.scrollLeft();
					header.css("left", scroller.cssv("left") - scroll);
				}
				if(scroller.scrollLeft() == 0) {
					header.css("position", "relative");
					header.css("left", "0px");
				}
		        return false;
			});		
			
			
			$(">tr", thead).each(function(){

				$(">th", this).each(function(i){
					var th = this, $th = $(this);
					$th.mouseover(function(event){
						
						var offset = $.jTableTool.getOffset(th, event).offsetX;
						/*if($th.outerWidth() - offset < 5) {
							$th.css("cursor", "col-resize").mousedown(function(event){
								
								$(".resizeProxy", $grid).show().css({
									left: $.jTableTool.getRight(th)- $(".gridScroller", $grid).scrollLeft(),
									top:$.jTableTool.getTop(th),
									height:$.jTableTool.getHeight(th,$grid),
									cursor:"col-resize"
								});
								$(".resizeMarker", $grid).show().css({
										left: $.jTableTool.getLeft(th) + 1 - $(".gridScroller", $grid).scrollLeft(),
										top: $.jTableTool.getTop(th),
										height:$.jTableTool.getHeight(th,$grid)									
								});
								$(".resizeProxy", $grid).jDrag($.extend(options, {scop:true, cellMinW:20, relObj:$(".resizeMarker", $grid)[0],
										move: "horizontal",
										event:event,
										stop: function(){
											var pleft = $(".resizeProxy", $grid).position().left;
											var mleft = $(".resizeMarker", $grid).position().left;
											var move = pleft - mleft - $th.outerWidth() -9;

											var cols = $.jTableTool.getColspan($th);
											var cellNum = $.jTableTool.getCellNum($th);
											var oldW = $th.width(), newW = $th.width() + move;
											var $dcell = $(">td", ftr).eq(cellNum - 1);
											
											$th.width(newW + "px");
											$dcell.width(newW+"px");
											
											var $table1 = $(thead).parent();
											$table1.width(($table1.width() - oldW + newW)+"px");
											var $table2 = $(tbody).parent();
											$table2.width(($table2.width() - oldW + newW)+"px");
											
											$(".resizeMarker,.resizeProxy", $grid).hide();
										}
									})
								);
							});
						} else {
							$th.css("cursor", $th.attr("orderField") ? "pointer" : "default");
							$th.unbind("mousedown");
						}*/
						return false;
					});
				});
			});
			
			
			function _bindUnlimitedTr(tr){
				
				var $tr = tr;
				
				$tr.find("[class$='collapsed'],[class$='expanded']").die().live('click',_changeUnlimitedTrState);
				
				$tr.find("div.checkbox").find("input:checkbox").live('click',_changeUnlimitedTrCheckboxState);
				
				
				function _changeUnlimitedTrCheckboxState(){
				//radio不需要级联选中状态 ，整个选择页面只能选择一个
				//checkbox需要选中页面，所以需要级联选中，选择中父节点，就会勾选上子孙节点
					
					var $checkbox = $(this);
					
					var checked   = $checkbox.attr('checked');
					
					var currentTrLeftNumber  = parseInt($tr.attr('left_number'));
					//得到用户发生的点击的时候所在行的左值
					 
					var currentTrRightNumber = parseInt($tr.attr('right_number'));
					//得到用户发生的点击的时候所在行的右值
					
					$tr.siblings('tr').each(function(){
					//遍历当前行所有兄弟节点
						
						var brotherTr = $(this);
						
						var brotherTrLeftNumber  = parseInt($(this).attr('left_number'));
						//当前行之后每一行的左值
						var brotherTrRightNumber = parseInt($(this).attr('right_number'));
						
						if( (brotherTrLeftNumber>currentTrLeftNumber) && ( brotherTrRightNumber < currentTrRightNumber)){
						//只有确定是后代节点才进行相关的选中操作
							
							if(checked=='checked'){
								brotherTr.find("div.checkbox").find("input:checkbox").attr('checked','checked');
							}
							else if(checked==undefined){
								brotherTr.find("div.checkbox").find("input:checkbox").removeAttr('checked');
							}
						}
						else if( (brotherTrLeftNumber < currentTrLeftNumber) && ( brotherTrRightNumber > currentTrRightNumber)){
							
							if(checked=='checked'){
								brotherTr.find("div.checkbox").find("input:checkbox").attr('checked','checked');
							}
							
						}
						
					});
					
					
				}//function _changeUnlimitedTrCheckboxState() end
				
				
				function _changeUnlimitedTrState(){
				//改变无限分类列表的单元行状态的函数
					
					var trClassString = $(this).attr('class');
					var trClassArray  = trClassString.split("_");
					var trState = trClassArray[1];
					
					if(trState=='collapsed'){
						_expandDescendantTr($(this));
					}
					else if(trState=='expanded'){
						_collapseDescendantTr($(this));
					}
					
				}//function _changeUnlimitedTrState() end
				
				
				function _expandDescendantTr(button){
				//扩展单元行
					
					var id  = parseInt($tr.attr('rel'));
					//得到用户发生的点击的时候所在行的id
					
					var sonTrList  =  new Array();
					
					$tr.nextAll('tr').each(function(){
						
						var parentId  = parseInt($(this).attr('parent_id'));
						//当前行之后每一行的父节点的数值
						
						if(id == parentId){
							sonTrList.push($(this).attr('rel'));
						}
					
					});
					
					if($(tr).attr('expanded_children_id_string')){
						
						var expandedChildrenIdString = $(tr).attr('expanded_children_id_string');
						
						var expandedChildrenIdArray  = expandedChildrenIdString.split(',');
						
						if(expandedChildrenIdArray.length>0 && sonTrList.length > 0){
							sonTrList = $.unique(    $.merge(sonTrList, expandedChildrenIdArray)       );
						}
						
					}
					
					
					if(sonTrList.length>0){
						
						$tr.nextAll('tr').each(function(){
							
							var rel =  $(this).attr('rel') ;
							
							if($.inArray(rel, sonTrList)>-1){
								$(this).css('display','table-row');
							}
							
						});
						
					}
					else{
						
						var PostURL = $table.attr('PostURL');
						
						if(PostURL==undefined){
							alert('没有提供为无限分类列表获取数据的方法，PostURL为空');
							return;
						}
						
						var PostData 		= new Object();
						    PostData['id']  = $tr.attr('rel');
						    
						if($table.attr('source')!=undefined){
							PostData['source'] = $table.attr('source'); 	
						}
						if($table.attr('form_element')!=undefined){
							PostData['form_element'] = $table.attr('form_element'); 	
						}
						if($table.attr('page_type')!=undefined){
							PostData['page_type'] = $table.attr('page_type'); 	
						}
						    
						$.post(PostURL, PostData,function(html){
							 
							 		Wrapedhtml = "<tbody>"+html+"</tbody>";
							 
									var count = $("tr",Wrapedhtml).length;
									
									$tr.after(html); 
									
									$tr.nextAll("tr:lt("+count+")").each(function(){
										
										var appendTr = $(this);
										//后台动态拉取的列表，最终是以append的方式追加到了后面
										
										_initUnlimitedTr(appendTr);
										_initNormalTr(appendTr);
										_bindUnlimitedTr(appendTr);
										_bindEachTrClickEvent(appendTr);
										
									});
									
									
						},'html');  
						
					}//else end
					
					var $button = button;
					var buttonClassString = $button.attr('class');
					var buttonClassArray  = buttonClassString.split("_");
					var TargetClass 	  = buttonClassArray[0]+"_"+'expanded';
					$button.attr('class',TargetClass);
					
				}//function _expandDescendantTr() end
				
				function _collapseDescendantTr(button){
				//收缩单元格
					
					var currentTrLeftNumber  = parseInt($tr.attr('left_number'));
					//得到用户发生的点击的时候所在行的左值
					 
					var currentTrRightNumber = parseInt($tr.attr('right_number'));
					//得到用户发生的点击的时候所在行的右值
					
					var id = parseInt(  $(tr).attr('rel') );
					//得到用户发生的点击的时候所在行的id
					
					var nextTrList  =  new Array();
					
					$tr.nextAll('tr').each(function(){
						
						var nextTrLeftNumber  = parseInt($(this).attr('left_number'));
						//当前行之后每一行的左值
						
						var nextTrRightNumber = parseInt($(this).attr('right_number'));
						//当前行之后每一行的右值
						
						if( (nextTrLeftNumber>currentTrLeftNumber) && ( nextTrRightNumber < currentTrRightNumber)){
							nextTrList.push($(this));
						}
						
					});
					
					var expandedChildrenIdList = new Array();
					//处于打开状态子孙行的id
					
					if(nextTrList.length>0){
						
						
						$.each(nextTrList,function(){
							
							var parent_id = parseInt( $(this).attr('parent_id') );
							
							if($(this).css('display')=='table-row' &&  parent_id != id){
								expandedChildrenIdList.push($(this).attr('rel'));
							}
							
							$(this).css('display','none');
						});
					}
					if(expandedChildrenIdList.length>0){
						$tr.attr('expanded_children_id_string',expandedChildrenIdList.join(','));
					}
					else{
						$tr.removeAttr('expanded_children_id_string');
					}
					
					
					var $button = button;
					var buttonClassString = $button.attr('class');
					var buttonClassArray  = buttonClassString.split("_");
					var TargetClass 	  = buttonClassArray[0]+"_"+'collapsed';
					$button.attr('class',TargetClass);
					
					
					
				}//function _collapseDescendantTr() end
				
				
			};//function _bindUnlimitedList() end
			
			function _bindEachTrClickEvent(tr){
				
				var $tr = tr;
				
				$tr.live('click',function(){
					
					$tr.siblings('tr.selected').removeClass('selected');
					
					$tr.addClass("selected");
					
					var sTarget = $tr.attr("target");
					
					if (sTarget) {
						
						if ($("#"+sTarget, $grid).size() == 0) {
							
							$grid.prepend('<input id="'+sTarget+'" type="hidden" />');
						}
						
						$("#"+sTarget, $grid).val($tr.attr("rel"));
					}
					
					
				});
				
			}//function _bindEachTr() end
			
			function _initNormalTr(tr){
			//针对于经过无限分类处理的或者是正常的单元行进行外面包裹一层div的需求
				
				var $tr   = tr;
				
				var $ftds = $(">td",$tr);

				for (var i=0; i < $ftds.size(); i++) {
					
					var $ftd = $($ftds[i]);
					
					if (nowrapTD != "false") $ftd.html("<div>" + $ftd.html() + "</div>");
					
					if (i < aStyles.length) $ftd.addClass(aStyles[i][1]);
				}
				
			};
			
			function _initUnlimitedTr(tr){
			//针对于每行无限分类的tr来进行操作，而不是所有的tr所进行的操作	
				
				var $tr = tr;
				//得到单元行每一行的对象
				
				var tr_Left_number  = $tr.attr('left_number');
				var tr_right_number = $tr.attr('right_number');
				var tr_level        = $tr.attr('level');
				
				if( isNaN(tr_Left_number) ||  isNaN(tr_right_number) ||  isNaN(tr_level) ){
					return false;
				}
				
				var diff = parseInt( tr_right_number- tr_Left_number -1);
				//计算左右值的差值
				
				var childrenList 	= new Array();
				
				var nextBrotherList = new Array();
				
				$tr.nextAll('tr').each(function(){
					
					tr_Left_number   = parseInt(tr_Left_number);
					tr_right_number  = parseInt(tr_right_number);
					
					var nextTrLeftNumber  = parseInt( $(this).attr('left_number') );
					var nextTrRightNumber = parseInt( $(this).attr('right_number') );
					
					if((nextTrLeftNumber>tr_Left_number)&&(nextTrRightNumber<tr_right_number)){
					//判断有没有孩子节点
						childrenList.push($(this));
					}
					else if((nextTrLeftNumber<tr_Left_number)&&(nextTrRightNumber>tr_right_number)){
					//判断有没有祖先节点
						//do nothing
					}
					else{
						nextBrotherList.push($(this));
					}
				});
				
				var prevState   = $tr.prev('tr').length;
				//前面只有有一行，就可以判定为有前置兄弟节点，而且不需要通过左右值来判断
				
				var nextState    = nextBrotherList.length;
				//判断有没有后面的兄弟的节点
				
				var hasChildren  = childrenList.length?true:false;
				//判断有没有孩子节点
				
				var only_state   = (prevState==0 && nextState==0)?1:0;
				//没有前置也没有后置
				
				var first_state  = (prevState==0 && nextState>0 )?1:0;
				//没有前置但是有后置
				
				var middle_state = (prevState>0  && nextState>0 )?1:0;
				//有前置也有后置
				
				var last_state   = (prevState>0  && nextState==0 )?1:0;
				//有前置没后置
				
				
				var string = '';
				
				if(diff>0){
				//如果大于0，那么就说明下面还有子区域，用文件夹图标表示
				
					string+= "<div class='indent'></div>";
					
					for(var i=0;i<tr_level;i++){
						string+= "<div class='line'></div>";
					}
					
					var class_string = '';
					
					if(only_state){
						class_string = 'only_collapsed';
						if(hasChildren){
							class_string = 'only_expanded';
						}
					}
					else if(first_state){
						class_string = 'first_collapsed';
						if(hasChildren){
							class_string = 'first_expanded';
						}
					}
					else if(middle_state){
						class_string = 'middle_collapsed';
						if(hasChildren){
							class_string = 'middle_expanded';
						}
					}
					else if(last_state){
						class_string = 'last_collapsed';
						if(hasChildren){
							class_string = 'last_expanded';
						}
					}
					
					string+= "<div class='"+ class_string+"'></div>";
					
				}
				else if(diff==0){
				//如果等于0，那么就说明下面没有子区域，用文件图标表示
					
					string+= "<div class='indent'></div>";
					
					for(var i=0;i<tr_level;i++){
						string+= "<div class='line'></div>";
					}
					
					string+= "<div class='node'></div>";
				
				}
				
				if($tr.find('div.checkbox').length>0){
					
					$tr.find('div.checkbox').before(string);
					
					if(diff>0){
						$tr.find('div.item').before("<div class='folder'></div>");
					}
					else{
						$tr.find('div.item').before("<div class='file'></div>");
					}
				
				}
				else if($tr.find('div.radio').length>0){
					
					$tr.find('div.radio').before(string);
					
					if(diff>0){
						$tr.find('div.item').before("<div class='folder'></div>");
					}
					else{
						$tr.find('div.item').before("<div class='file'></div>");
					}
				
				}
				else{
					
					if(diff>0){
						string+= "<div class='folder'></div>";
					}
					else{
						string+= "<div class='file'></div>";
					}
					
					$tr.find('div.item').before(string);
					
				}
				
				
				
			}//function _initUnlimitedList() end
			
			function _resizeGrid(){
				$("div.j-resizeGrid").each(function(){
					var width = $(this).innerWidth();
					if (width){
						$("div.gridScroller", this).width(width+"px");
					}
				});
			};
			
			
			
			$(window).unbind("resizeGrid").bind("resizeGrid", _resizeGrid);
		});
	};
	
	
	$.jTableTool = {
		getLeft:function(obj) {
			var width = 0;
			$(obj).prevAll().each(function(){
				width += $(this).outerWidth();
			});
			return width - 1;
		},
		getRight:function(obj) {
			var width = 0;
			$(obj).prevAll().andSelf().each(function(){
				width += $(this).outerWidth();
			});
			return width - 1;
		},
		getTop:function(obj) {
			var height = 0;
			$(obj).parent().prevAll().each(function(){
				height += $(this).outerHeight();
			});
			return height;
		},
		getHeight:function(obj, parent) {
			var height = 0;
			var head = $(obj).parent();
			head.nextAll().andSelf().each(function(){
				height += $(this).outerHeight();
			});
			$(".gridTbody", parent).children().each(function(){
				height += $(this).outerHeight();
			});
			return height;
		},
		getCellNum:function(obj) {
			return $(obj).prevAll().andSelf().size();
		},
		getColspan:function(obj) {
			return $(obj).attr("colspan") || 1;
		},
		getStart:function(obj) {
			var start = 1;
			$(obj).prevAll().each(function(){
				start += parseInt($(this).attr("colspan") || 1);
			});
			return start;
		},
		getPageCoord:function(element){
			var coord = {x: 0, y: 0};
			while (element){
			    coord.x += element.offsetLeft;
			    coord.y += element.offsetTop;
			    element = element.offsetParent;
			}
			return coord;
		},
		getOffset:function(obj, evt){
			if($.browser.msie ) {
				var objset = $(obj).offset();
				var evtset = {
					offsetX:evt.pageX || evt.screenX,
					offsetY:evt.pageY || evt.screenY
				};
				var offset ={
			    	offsetX: evtset.offsetX - objset.left,
			    	offsetY: evtset.offsetY - objset.top
				};
				return offset;
			}
			var target = evt.target;
			if (target.offsetLeft == undefined){
			    target = target.parentNode;
			}
			var pageCoord = $.jTableTool.getPageCoord(target);
			var eventCoord ={
			    x: window.pageXOffset + evt.clientX,
			    y: window.pageYOffset + evt.clientY
			};
			var offset ={
			    offsetX: eventCoord.x - pageCoord.x,
			    offsetY: eventCoord.y - pageCoord.y
			};
			return offset;
		}
	};
})(jQuery);
